package com.wyh.rabbitextensionsdemo.listener;

import com.rabbitmq.client.Channel;
import com.wyh.rabbitextensionsdemo.constant.Constants;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class Listener {
    @RabbitListener(queues = Constants.ACK_QUEUE)
    public void handler1(Message msg, Channel channel) throws IOException {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            System.out.println("接收消息：" + new String(msg.getBody()) + msg.getMessageProperties().getDeliveryTag());
            int n = 3/0;
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            channel.basicNack(deliveryTag,false,true);
        }
    }

    @RabbitListener(queues = Constants.NORMAL_QUEUE)
    public void handler2 (Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.printf("接收消息成功：%s , ID: %d", new String(message.getBody()),deliveryTag);
//            int n = 3/0;
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            System.out.printf("消息处理失败：%d",deliveryTag);
            channel.basicNack(deliveryTag,false,false);
        }
    }

    @RabbitListener(queues = Constants.DELAY_QUEUE)
    public void handler3(Message msg, Channel channel) {
        System.out.println("接收到消息：" + new Date());
    }

    @RabbitListener(queues = Constants.QOS_QUEUE)
    public void qosHandler(Message msg) throws IOException {
        System.out.println("接收到消息：" + msg);
//        channel.basicAck(msg.getMessageProperties().getDeliveryTag(),false);
//        channel.basicNack(msg.getMessageProperties().getDeliveryTag(),false,true);
    }
}
